<template>
  <div
    v-loading="loading"
    class=""
  >
    <!-- 表单 start -->
    <div class="form-container">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="small"
        label-width="140px"
        label-suffix="："
        class="demo-ruleForm"
      >
        <!--商品基础-->
        <div class="base-content">
          <!-- 头部-->
          <div class="flex-x-start-center">
            <AppMainTitle :title="mode === 'edit' ? '编辑商品' : '新增商品'" :margin-bottom="0" />
            <el-button-group style="margin-left: 20px">
              <el-button
                size="small"
                round
                @click="back"
              >返回
              </el-button>
              <el-button
                type="primary"
                size="small"
                round
                @click="submit"
              >保存
              </el-button>
            </el-button-group>
          </div>
          <el-divider />
          <div class="flex-x-start">
            <div>
              <el-form-item
                label="商品标题"
                prop="title"
              >
                <el-input
                  v-model="form.title"
                  :rows="4"
                  type="textarea"
                  maxlength="60"
                  show-word-limit
                  class="w-400"
                />
              </el-form-item>
            </div>
            <div>
              <el-form-item
                label="商品类目"
                prop="categoryIds"
                class="inline-block"
              >
                <el-cascader
                  v-model="form.categoryIds"
                  :options="categoryTreeOptions"
                  :show-all-levels="false"
                  :props="{
                    expandTrigger: 'hover',
                    checkStrictly: true,
                    label: 'title',
                    value: 'id',
                  }"
                  class="w-400"
                />
              </el-form-item>
              <el-form-item
                label="商品类型"
                prop="goodsType"
              >
                <el-select
                  v-model="form.goodsType"
                  :disabled="mode === 'edit'"
                  value-key="id"
                  placeholder="请选择"
                  class="w-400"
                  @change="changeGoodsType"
                >
                  <el-option
                    v-for="(v,k) in goodsTypeOptions"
                    :key="k"
                    :label="v"
                    :value="Number(k)"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="tab-content">
            <el-tabs v-model="tabName" @tab-click="tabClick">
              <template v-for="(v,k) in tabOptions">
                <el-tab-pane v-if="v.goodsType.includes(form.goodsType)" :key="k" :label="v.label" :name="k" />
              </template>
            </el-tabs>
          </div>
        </div>
        <!--商品附加-->
        <div class="additional-content">
          <!--规格 start-->
          <div v-show="tabName==='specs'">
            <div v-if="tabOptions['specs'].goodsType.includes(form.goodsType)">
              <el-form-item
                v-if="form.goodsType === 100"
                label="销售属性"
                prop="specList"
              >
                <el-card
                  v-for="(item, index) in form.specList"
                  :key="'spec-' + index"
                  class="spec-card"
                >
                  <div
                    slot="header"
                    class="clearfix"
                  >
                    <span>{{ item.title }}</span>
                    <el-button
                      style="float: right"
                      type="text"
                      @click="delSpec(index)"
                    >删除
                    </el-button>
                  </div>
                  <el-form-item
                    :prop="'specList.' + index + '.attrList'"
                    :rules="rules.attrList"
                  >
                    <el-tag
                      v-for="(tagItem, tagIndex) in item.attrList"
                      :key="'attr-' + tagIndex"
                      :disable-transitions="false"
                      closable
                      @close="closeAttr(item.attrList, tagIndex)"
                    >{{ tagItem.title }}
                    </el-tag>
                    <div>
                      <el-input
                        v-if="item.inputVisible"
                        ref="saveAttrInput"
                        v-model="item.inputValue"
                        class="w-450-h-32"
                        size="small"
                        placeholder="请输入属性选项"
                        maxlength="30"
                        show-word-limit
                        @keyup.enter.native="addAttr(item)"
                        @blur="addAttr(item)"
                      />
                      <el-button
                        v-else
                        size="small"
                        style="height: 32px"
                        @click="showAttrInput(item)"
                      >+ 增加类目属性选项
                      </el-button>
                    </div>
                  </el-form-item>
                </el-card>
                <el-button
                  :disabled="form.specList.length >= 3"
                  type="primary"
                  round
                  icon="el-icon-plus"
                  @click="openCategory"
                >从类目选择属性
                </el-button>
                <el-input
                  v-if="specInputVisible"
                  ref="saveSpecInput"
                  v-model="form.specInputValueExcl"
                  class="w-300-h-32"
                  size="small"
                  placeholder="请输入属性名"
                  style="margin-left:10px"
                  maxlength="10"
                  show-word-limit
                  @keyup.enter.native="addSpec"
                  @blur="addSpec"
                />
                <el-button
                  v-else
                  :disabled="form.specList.length >= 3"
                  type="primary"
                  round
                  icon="el-icon-plus"
                  @click="showSpecInput"
                >增加自定义属性
                </el-button>
              </el-form-item>
              <div>
                <el-form-item
                  label="商品编码"
                  prop="goodsNo"
                  class="inline-block"
                >
                  <el-input
                    v-model.trim="form.goodsNo"
                    class="w-300"
                    maxlength="30"
                    show-word-limit
                    placeholder="内部标识"
                  />
                </el-form-item>
                <el-form-item
                  label="国际条码"
                  prop="barCode"
                  class="inline-block"
                >
                  <el-input
                    v-model.trim="form.barCode"
                    class="w-300"
                    maxlength="30"
                    show-word-limit
                    placeholder="用户单品优惠"
                  />
                </el-form-item>
              </div>

              <!-- 单个销售属性  start-->
              <div v-if="form.skuList.length === 1">
                <div>
                  <el-form-item
                    :rules="rules.price"
                    label="销售价"
                    class="inline-block"
                    prop="skuList.0.price"
                  >
                    <el-input
                      v-model.trim="form.skuList[0].price"
                      class="w-300"
                      maxlength="10"
                    >
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item
                    :rules="rules.originPrice"
                    label="市场价"
                    class="inline-block"
                    prop="skuList.0.originPrice"
                  >
                    <el-input
                      v-model.trim="form.skuList[0].originPrice"
                      class="w-300"
                      maxlength="10"
                    >
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                </div>
                <el-form-item
                  label="上架状态"
                  prop="skuList.0.status"
                >
                  <el-switch
                    v-model="form.skuList[0].status"
                    :active-value="1"
                    :inactive-value="0"
                    inactive-color="#ff4949"
                  />
                  <span v-if="form.skuList[0].status">上架</span>
                  <span v-else>下架</span>
                </el-form-item>
              </div>
              <!-- 单个销售属性 end -->

              <!-- 多个销售属性 start-->
              <div v-if="form.skuList.length > 1">
                <el-form-item
                  label="销售价格"
                >
                  <el-button
                    type="text"
                    icon="el-icon-plus"
                    style="height: 32px"
                    @click="openDialogPrice"
                  >批量改价
                  </el-button>
                  <el-table
                    :data="form.skuList"
                    border
                    stripe
                    size="small"
                    element-loading-text="加载中"
                    empty-text="暂无sku"
                  >
                    <el-table-column
                      v-if="form.specList.length"
                      prop="nickName"
                      label="属性"
                    >
                      <template slot-scope="scope">
                        <span
                          v-if="
                            !scope.row.specAttrNameList ||
                              scope.row.specAttrNameList.length === 0
                          "
                        >无属性</span>
                        <span
                          v-for="(attr, attrIndex) in scope.row.specAttrNameList"
                          :key="attrIndex"
                        >
                          {{ attr }}
                          <span
                            v-if="attrIndex + 1 !== scope.row.specAttrNameList.length"
                          >/</span>
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="status"
                      label="上架状态"
                      width="120"
                    >
                      <template slot-scope="scope">
                        <el-switch
                          v-model="scope.row.status"
                          :active-value="1"
                          :inactive-value="0"
                          inactive-color="#ff4949"
                        />
                        <span v-if="scope.row.status">上架</span>
                        <span v-else>下架</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="price"
                      label="* 销售价/元"
                      width="180"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'skuList.' + scope.$index + '.price'"
                          :rules="rules.price"
                          class="m-t-18"
                        >
                          <el-input
                            v-model.trim="scope.row.price"
                            maxlength="10"
                          >
                            <template slot="append">元</template>
                          </el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="originPrice"
                      label="市场价/元"
                      width="180"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'skuList.' + scope.$index + '.originPrice'"
                          :rules="rules.originPrice"
                          class="m-t-18"
                        >
                          <el-input
                            v-model.trim="scope.row.originPrice"
                            maxlength="10"
                          >
                            <template slot="append">元</template>
                          </el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="skuNo"
                      label="SKU编码"
                      width="300"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'skuList.' + scope.$index + '.skuNo'"
                          class="m-t-18"
                        >
                          <el-input
                            v-model.trim="scope.row.skuNo"
                            maxlength="30"
                            show-word-limit
                            placeholder="内部标识"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="sn"
                      label="国际条码"
                      width="300"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'skuList.' + scope.$index + '.sn'"
                          class="m-t-18"
                        >
                          <el-input
                            v-model.trim="scope.row.sn"
                            maxlength="30"
                            show-word-limit
                            placeholder="用户单品优惠"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="imgUrl"
                      label="SKU图片"
                      width="130"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'skuList.' + scope.$index + '.imgUrl'"
                          class="m-t-18"
                        >
                          <div class="flexRBC">
                            <el-upload
                              :action="imageUploadUrl"
                              :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                              :before-upload="handleSkuImgBefore"
                              :on-success="
                                (res, file) => {
                                  return handleSkuImgSuccess(res, file, scope.$index);
                                }
                              "
                              :show-file-list="false"
                            >
                              <el-button
                                size="small"
                                type="text"
                              >上传
                              </el-button>
                            </el-upload>
                            <div class="sku-img">
                              <img
                                v-if="scope.row.imgUrl"
                                :src="fileBaseUrl + scope.row.imgUrl"
                                class="avatar"
                              >
                            </div>
                          </div>
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </div>
              <!-- 多个销售属性 end-->
            </div>
          </div>
          <!--规格 end-->

          <!--配送 start-->
          <div v-show="tabName==='delivery'">
            <div v-if="tabOptions['delivery'].goodsType.includes(form.goodsType)">
              <div>
                <el-form-item
                  label="快递物流"
                  style="margin-bottom: 0"
                >
                  <el-form-item class="app-display-i-b" prop="goodsDelivery">
                    <el-select
                      v-model="form.goodsDelivery.canExpress"
                      placeholder="请选择"
                      class="w-300"
                    >
                      <el-option
                        :value="true"
                        label="支持，默认不设置备货时间"
                      />
                      <el-option
                        value="truePrepare"
                        label="支持，并设置备货时间"
                      />
                      <el-option
                        :value="false"
                        label="不支持"
                      />
                    </el-select>
                  </el-form-item>
                  <div v-if="form.goodsDelivery.canExpress==='truePrepare'" class="app-display-i-b">
                    <span>&nbsp;&nbsp;购买下单后最快&nbsp;</span>
                    <el-form-item :rules="rules.deliveryPrepare" class="app-display-i-b" prop="goodsDelivery.expressPrepare">
                      <el-input
                        v-model="form.goodsDelivery.expressPrepare"
                        class="w-100"
                        maxlength="3"
                        placeholder="请输入"
                      />
                    </el-form-item>
                    <el-form-item class="app-display-i-b" prop="goodsDelivery.expressPrepareUnit">
                      <el-select
                        v-model="form.goodsDelivery.expressPrepareUnit"
                        placeholder="请选择"
                        class="w-100"
                      >
                        <el-option
                          value="HOURS"
                          label="小时"
                        />
                        <el-option
                          value="DAYS"
                          label="天"
                        />
                        <el-option
                          value="MINUTES"
                          label="分钟"
                        />
                      </el-select>
                    </el-form-item>
                    <span>&nbsp;完成备货</span>
                  </div>
                </el-form-item>
              </div>
              <div>
                <el-form-item
                  label="同城配送"
                  style="margin-bottom: 0"
                >
                  <el-form-item class="app-display-i-b" prop="goodsDelivery">
                    <el-select
                      v-model="form.goodsDelivery.canLocalDelivery"
                      placeholder="请选择"
                      class="w-300"
                    >
                      <el-option
                        :value="true"
                        label="支持，默认不设置备货时间"
                      />
                      <el-option
                        value="truePrepare"
                        label="支持，并设置备货时间"
                      />
                      <el-option
                        :value="false"
                        label="不支持"
                      />
                    </el-select>
                  </el-form-item>
                  <div v-if="form.goodsDelivery.canLocalDelivery==='truePrepare'" class="app-display-i-b">
                    <span>&nbsp;&nbsp;购买下单后最快&nbsp;</span>
                    <el-form-item :rules="rules.deliveryPrepare" class="app-display-i-b" prop="goodsDelivery.localPrepare">
                      <el-input
                        v-model="form.goodsDelivery.localPrepare"
                        class="w-100"
                        maxlength="3"
                        placeholder="请输入"
                      />
                    </el-form-item>
                    <el-form-item class="app-display-i-b" prop="goodsDelivery.localPrepareUnit">
                      <el-select
                        v-model="form.goodsDelivery.localPrepareUnit"
                        placeholder="请选择"
                        class="w-100"
                      >
                        <el-option
                          value="HOURS"
                          label="小时"
                        />
                        <el-option
                          value="DAYS"
                          label="天"
                        />
                        <el-option
                          value="MINUTES"
                          label="分钟"
                        />
                      </el-select>
                    </el-form-item>
                    <span>&nbsp;完成备货</span>
                  </div>
                </el-form-item>
              </div>
              <div>
                <el-form-item
                  label="到店自提"
                  style="margin-bottom: 0"
                >
                  <el-form-item class="app-display-i-b" prop="goodsDelivery">
                    <el-select
                      v-model="form.goodsDelivery.canSelfPickup"
                      placeholder="请选择"
                      class="w-300"
                    >
                      <el-option
                        :value="true"
                        label="支持，默认不设置备货时间"
                      />
                      <el-option
                        value="truePrepare"
                        label="支持，并设置备货时间"
                      />
                      <el-option
                        :value="false"
                        label="不支持"
                      />
                    </el-select>
                  </el-form-item>
                  <div v-if="form.goodsDelivery.canSelfPickup==='truePrepare'" class="app-display-i-b">
                    <span>&nbsp;&nbsp;购买下单后最快&nbsp;</span>
                    <el-form-item :rules="rules.deliveryPrepare" class="app-display-i-b" prop="goodsDelivery.selfPickupPrepare">
                      <el-input
                        v-model="form.goodsDelivery.selfPickupPrepare"
                        class="w-100"
                        maxlength="3"
                        placeholder="请输入"
                      />
                    </el-form-item>
                    <el-form-item class="app-display-i-b" prop="goodsDelivery.selfPickupPrepareUnit">
                      <el-select
                        v-model="form.goodsDelivery.selfPickupPrepareUnit"
                        placeholder="请选择"
                        class="w-100"
                      >
                        <el-option
                          value="HOURS"
                          label="小时"
                        />
                        <el-option
                          value="DAYS"
                          label="天"
                        />
                        <el-option
                          value="MINUTES"
                          label="分钟"
                        />
                      </el-select>
                    </el-form-item>
                    <span>&nbsp;完成备货</span>
                  </div>
                </el-form-item>
              </div>
            </div>

          </div>
          <!--配送 end-->

          <!--卡券 start-->
          <div v-show="tabName==='coupon'">
            <div v-if="tabOptions['coupon'].goodsType.includes(form.goodsType)">
              <div>
                <el-form-item
                  label="商品编码"
                  prop="goodsNo"
                  class="inline-block"
                >
                  <el-input
                    v-model.trim="form.goodsNo"
                    class="w-300"
                    maxlength="30"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item
                  label="国际条码"
                  prop="barCode"
                  class="inline-block"
                >
                  <el-input
                    v-model.trim="form.barCode"
                    class="w-300"
                    maxlength="30"
                    show-word-limit
                  />
                </el-form-item>
              </div>
              <!-- 单个销售属性  start-->
              <div v-if="form.skuList.length === 1">
                <div>
                  <el-form-item
                    :rules="rules.price"
                    label="销售价"
                    class="inline-block"
                    prop="skuList.0.price"
                  >
                    <el-input
                      v-model.trim="form.skuList[0].price"
                      class="w-300"
                      maxlength="10"
                    >
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item
                    :rules="rules.originPrice"
                    label="市场价"
                    class="inline-block"
                    prop="skuList.0.originPrice"
                  >
                    <el-input
                      v-model.trim="form.skuList[0].originPrice"
                      class="w-300"
                      maxlength="10"
                    >
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                </div>
                <el-form-item
                  label="上架状态"
                  prop="skuList.0.status"
                >
                  <el-switch
                    v-model="form.skuList[0].status"
                    :active-value="1"
                    :inactive-value="0"
                    inactive-color="#ff4949"
                  />
                  <span v-if="form.skuList[0].status">上架</span>
                  <span v-else>下架</span>
                </el-form-item>
              </div>
              <!-- 单个销售属性 end -->
              <el-form-item
                label="卡券"
                prop="goodsItems"
              >
                <el-radio-group
                  v-model="form.couponVerRadio"
                  @change="couponVerRadioChange"
                >
                  <el-radio label="COUPON2">兑换卡券</el-radio>
                  <el-radio label="COUPON" disabled>兑换券(已弃用)</el-radio>
                </el-radio-group>
                <div class="card-coupon-container">
                  <el-table
                    :data="form.goodsItems"
                    border
                    stripe
                    size="small"
                    empty-text="暂未配置"
                    style="width: 100%"
                  >
                    <el-table-column
                      prop="itemId"
                      label="批次号"
                    />
                    <el-table-column
                      prop="itemTitle"
                      label="卡券名称"
                    />
                    <el-table-column
                      prop="num"
                      label="数量"
                      width="170px"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'goodsItems[' + scope.$index + '].num'"
                          :rules="rules.couponNum"
                        >
                          <el-input-number
                            v-model="scope.row.num"
                            :min="1"
                            :max="99"
                            maxlength="2"
                            label="数量"
                            style="margin-top: 18px"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      width="80"
                    >
                      <template slot-scope="scope">
                        <el-button
                          type="text"
                          @click="delCardCoupon(scope.$index)"
                        >删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button
                    v-if="form.couponVerRadio==='COUPON2'"
                    :disabled="form.goodsItems.length>=10"
                    type="text"
                    icon="el-icon-plus"
                    style="display:block"
                    @click.native.prevent="openDialogCardCouponTable"
                  >增加卡券
                  </el-button>
                  <!--<el-button-->
                  <!--  v-if="form.couponVerRadio==='COUPON'"-->
                  <!--  :disabled="form.goodsItems.length>=10"-->
                  <!--  type="text"-->
                  <!--  icon="el-icon-plus"-->
                  <!--  style="display:block"-->
                  <!--  @click.native.prevent="openCouponList"-->
                  <!--&gt;增加券-->
                  </el-button>
                  <div class="tips">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
                </div>
              </el-form-item>
            </div>
          </div>

          <!--卡券 end-->

          <!--参数 start-->
          <div v-show="tabName==='param'">
            <div v-if="tabOptions['param'].goodsType.includes(form.goodsType)">
              <div>
                <el-form-item
                  :inline="true"
                  label="商品品牌"
                  prop="brandId"
                  class="inline-block"
                >
                  <el-select
                    v-model="form.brandId"
                    placeholder="请选择"
                    class="w-300"
                  >
                    <el-option
                      :value="0"
                      label="默认品牌"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :inline="true"
                  label="商品单位"
                  class="inline-block"
                  prop="goodsUnit"
                >
                  <el-input
                    v-model.trim="form.goodsUnit"
                    class="w-300 "
                    maxlength="5"
                    show-word-limit
                  />
                </el-form-item>
              </div>
            </div>

            <el-form-item
              label="商品描述"
              prop="description"
            >
              <el-input
                v-model="form.description"
                :rows="6"
                type="textarea"
                class="w-300"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="商品参数">
              <div
                v-for="(item, index) in form.goodsExt.paramList"
                :key="index"
              >
                <el-form-item
                  :prop="'goodsExt.paramList.' + index + '.name'"
                  :rules="rules.paramsName"
                  style="display: inline-block"
                >
                  <el-input
                    v-model.trim="item.name"
                    placeholder="请输入参数名称"
                    class="w-200"
                    maxlength="10"
                  />
                </el-form-item>
                <el-form-item
                  :prop="'goodsExt.paramList.' + index + '.value'"
                  :rules="rules.paramsValue"
                  style="display: inline-block"
                >
                  <el-input
                    v-model.trim="item.value"
                    placeholder="请输入参数内容"
                    class="w-300"
                    maxlength="100"
                  />
                </el-form-item>
                <el-button
                  type="text"
                  icon="el-icon-minus"
                  style="height: 32px"
                  @click="delParams(index)"
                >删除
                </el-button>
              </div>
              <el-button
                type="primary"
                round
                icon="el-icon-plus"
                style="height: 32px"
                @click="addParams"
              >增加自定义参数
              </el-button>
            </el-form-item>
          </div>
          <!--参数 end-->

          <!--服务 start-->
          <div v-show="tabName==='service'">
            <div v-if="tabOptions['param'].goodsType.includes(form.goodsType)">
              <el-form-item label="商品服务">
                <el-select
                  v-model="form.goodsExt.supportList"
                  value-key="id"
                  multiple
                  clearable
                  placeholder="请选择"
                  style="width: 500px"
                >
                  <el-option
                    v-for="item in supportListOptions"
                    :key="item.id"
                    :label="item.title"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <!--服务 end-->

          <!--图册 start-->
          <div v-show="tabName==='photo'">
            <div v-if="tabOptions['photo'].goodsType.includes(form.goodsType)">
              <el-form-item
                prop="displayInfo.imageList"
                label="商品图片"
              >
                <div class="upload-img-list-container">
                  <draggable
                    :list="form.displayInfo.imageList"
                    :options="{ filter: '.undrag' }"
                  >
                    <div
                      v-for="(v, i) in form.displayInfo.imageList"
                      :key="i"
                      class="img-item drag"
                    >
                      <el-image
                        :src="v.url"
                        style="width: 100%; height: 100%"
                        fit="contain"
                      />
                      <div class="handle-icon">
                        <i
                          class="el-icon-zoom-in icon"
                          @click="handlePreview(v)"
                        />
                        <i
                          class="el-icon-delete icon"
                          @click="handleImageListRemove(v, i)"
                        />
                      </div>
                    </div>

                    <div class="img-item undrag">
                      <el-upload
                        :limit="10"
                        :action="imageUploadUrl"
                        :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                        :file-list="form.displayInfo.imageList"
                        :before-upload="handleDisplayInfoBefore"
                        :on-success="handleImageListSuccess"
                        :on-exceed="handleExceed"
                        :show-file-list="false"
                        drag
                        multiple
                        list-type="picture-card"
                        class="upload-container"
                      >
                        <i class="el-icon-upload" />
                        <div class="el-upload__text">
                          将文件拖到此处，或
                          <em>点击上传</em>
                        </div>
                      </el-upload>
                      <el-dialog
                        :visible.sync="dialogImageVisible"
                        title="图片预览"
                      >
                        <img
                          :src="dialogImageUrl"
                          width="100%"
                          alt
                        >
                      </el-dialog>
                    </div>
                  </draggable>
                </div>
                <div class="upload-tips app-tips">
                  <div>1.只能上传jpg/png文件,且不超过1mb</div>
                  <div>2.建议1000*1000像素内,长宽比是 1:1</div>
                  <div>3.最多上传10张,可长按图片进行拖拽排序</div>
                </div>
              </el-form-item>
              <!-- <el-form-item label="商品视频" prop="name"></el-form-item> -->
              <el-form-item
                label="详情图片"
                prop="name"
              >
                <div class="upload-img-list-container">
                  <draggable
                    :list="form.displayInfo.detailImages"
                    :options="{ filter: '.undrag' }"
                  >
                    <div
                      v-for="(v, i) in form.displayInfo.detailImages"
                      :key="i"
                      class="img-item drag"
                    >
                      <el-image
                        :src="v.url"
                        style="width: 100%; height: 100%"
                        fit="contain"
                      />
                      <div class="handle-icon">
                        <i
                          class="el-icon-zoom-in icon"
                          @click="handlePreview(v)"
                        />
                        <i
                          class="el-icon-delete icon"
                          @click="handleDetailImagesRemove(v, i)"
                        />
                      </div>
                    </div>

                    <div class="img-item undrag">
                      <el-upload
                        :limit="10"
                        :action="imageUploadUrl"
                        :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                        :file-list="form.displayInfo.detailImages"
                        :before-upload="handleDisplayInfoBefore"
                        :on-success="handleDetailImagesSuccess"
                        :on-exceed="handleExceed"
                        :show-file-list="false"
                        drag
                        multiple
                        list-type="picture-card"
                        class="upload-container"
                      >
                        <i class="el-icon-upload" />
                        <div class="el-upload__text">
                          将文件拖到此处，或
                          <em>点击上传</em>
                        </div>
                      </el-upload>
                      <el-dialog
                        :visible.sync="dialogImageVisible"
                        title="图片预览"
                      >
                        <img
                          :src="dialogImageUrl"
                          width="100%"
                          alt
                        >
                      </el-dialog>
                    </div>
                  </draggable>
                </div>
                <div class="upload-tips app-tips">
                  <div>1.只能上传jpg/png文件，且不超过1mb</div>
                  <div>2.最多上传10张</div>
                  <div>3.可长按图片进行拖拽排序</div>
                </div>
              </el-form-item>
            </div>
          </div>
          <!--图册 end-->

          <!--预售 start-->
          <div v-show="tabName==='preSale'">
            <div v-if="tabOptions['preSale'].goodsType.includes(form.goodsType)">
              <el-form-item
                label="商品销售模式"
                prop="presell"
              >
                <el-select
                  v-model="form.presell"
                  placeholder="现货销售"
                  style="margin-bottom:6px"
                >
                  <el-option
                    :value="false"
                    label="现货销售"
                  />
                  <el-option
                    :value="true"
                    label="商品预售"
                  />
                </el-select>
              </el-form-item>
              <el-collapse-transition>
                <div v-if="form.presell">
                  <el-form-item
                    label="商品预售模式"
                    prop="goodsPresell.type"
                  >
                    <el-select
                      v-model="form.goodsPresell.type"
                      placeholder="请选择"
                      style="margin-bottom:6px"
                      @change="goodsPresellTypeChange"
                    >
                      <el-option
                        value="FULL"
                        label="全款预售"
                      />
                      <el-option
                        value="DEPOSIT"
                        label="定金预售"
                      />
                    </el-select>
                    <div v-if="form.goodsPresell.type==='DEPOSIT'">
                      <span>&nbsp;预售下单支付&nbsp;</span>
                      <el-form-item class="app-display-i-b" prop="goodsPresell.depositType">
                        <el-select
                          v-model="form.goodsPresell.depositType"
                          placeholder="请选择"
                          style="margin-bottom:6px"
                          class="w-100"
                        >
                          <el-option
                            :value="0"
                            label="固定定金"
                          />
                          <el-option
                            :value="1"
                            label="比例定金"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        v-if="form.goodsPresell.depositType===0"
                        class="app-display-i-b"
                        prop="goodsPresell.depositQuota"
                      >
                        <el-input
                          v-model="form.goodsPresell.depositQuota"
                          class="w-200"
                          maxlength="10"
                          placeholder="请输入"
                        >
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                      <el-form-item
                        v-if="form.goodsPresell.depositType===1"
                        class="app-display-i-b"
                        prop="goodsPresell.depositQuota"
                      >
                        <el-input
                          v-model="form.goodsPresell.depositQuota"
                          class="w-200"
                          maxlength="10"
                          placeholder="请输入"
                        >
                          <template slot="append">%</template>
                        </el-input>
                        <span class="tips">&nbsp;计算后金额会向上取整到元， eg.定金0.1元会要求支付1元, 定金低于1元请使用固定金额模式</span>
                      </el-form-item>
                    </div>
                  </el-form-item>
                  <el-form-item
                    label="预售时间"
                    prop="goodsPresell.limitTime"
                  >
                    <el-select
                      v-model="form.goodsPresell.limitTime"
                      placeholder="请选择"
                      style="margin-bottom:6px"
                    >
                      <el-option
                        :value="true"
                        label="指定日期"
                      />
                      <el-option
                        :disabled="form.goodsPresell.type!=='FULL'"
                        :value="false"
                        label="长期支持预售(限全款预售)"
                      />
                    </el-select>
                    <el-collapse-transition>
                      <div v-if="form.goodsPresell.limitTime === true">
                        <el-card>
                          <el-form-item class="app-display-i-b" prop="goodsPresell.preDate">
                            <el-date-picker
                              v-model="form.goodsPresell.preDate"
                              type="daterange"
                              range-separator="~"
                              value-format="yyyy-MM-dd"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                            />
                          </el-form-item>
                          <span>&nbsp;开启预售，到期后&nbsp;</span>
                          <el-form-item class="app-display-i-b" prop="goodsPresell.afterTheEnd">
                            <el-select
                              v-model="form.goodsPresell.afterTheEnd"
                              placeholder="请选择"
                              style="margin-bottom:6px"
                            >
                              <el-option
                                :value="0"
                                label="关闭预售"
                              />
                              <el-option
                                :value="1"
                                label="自动下架"
                              />
                            </el-select>
                          </el-form-item>
                        </el-card>
                      </div>
                    </el-collapse-transition>
                  </el-form-item>
                  <el-form-item
                    v-if="form.goodsPresell.type==='DEPOSIT'"
                    label="尾款支付"
                    class="is-required"
                  >
                    <div>
                      <el-card>
                        <div>
                          <el-form-item class="app-display-i-b" prop="goodsPresell.remainingBeginTime">
                            <el-date-picker
                              v-model="form.goodsPresell.remainingBeginTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择日期时间"
                            />
                          </el-form-item>
                          <span>&nbsp;可以开始支付尾款，&nbsp;</span>
                          <el-form-item class="app-display-i-b" prop="goodsPresell.remainingEndTime">
                            <el-date-picker
                              v-model="form.goodsPresell.remainingEndTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择日期时间"
                            />
                          </el-form-item>
                          <span>&nbsp;前完成尾款支付</span>
                          <div>
                            <span>逾期未支付尾款订单关闭订单且&nbsp;</span>
                            <el-form-item class="app-display-i-b" prop="goodsPresell.defaultRule">
                              <el-select
                                v-model="form.goodsPresell.defaultRule"
                                placeholder="请选择"
                                class="w-200"
                              >
                                <el-option
                                  :value="0"
                                  label="顾客免责"
                                />
                                <el-option
                                  :value="1"
                                  label="顾客全责"
                                />
                                <el-option
                                  :value="2"
                                  label="扣除违约金"
                                />
                              </el-select>
                            </el-form-item>

                            <span v-if="form.goodsPresell.defaultRule===0">，退还已支付定金</span>
                            <span v-if="form.goodsPresell.defaultRule===1">，不退还已支付定金</span>
                            <div
                              v-if="form.goodsPresell.defaultRule===2"
                              class="app-display-i-b"
                            >
                              <el-form-item class="app-display-i-b" prop="goodsPresell.defaultFineType">
                                <el-select
                                  v-model="form.goodsPresell.defaultFineType"
                                  placeholder="请选择"
                                  class="w-100"
                                >
                                  <el-option
                                    :value="0"
                                    label="固定金额"
                                  />
                                  <el-option
                                    :value="1"
                                    label="一定比例"
                                  />
                                </el-select>
                              </el-form-item>
                              <span>&nbsp;违约金为&nbsp;</span>
                              <el-form-item
                                v-if="form.goodsPresell.defaultFineType===0"
                                class="app-display-i-b"
                                prop="goodsPresell.defaultFine"
                              >
                                <el-input
                                  v-model="form.goodsPresell.defaultFine"
                                  class="w-200"
                                  placeholder="请输入"
                                >
                                  <template slot="append">元</template>
                                </el-input>
                              </el-form-item>
                              <el-form-item
                                v-if="form.goodsPresell.defaultFineType===1"
                                class="app-display-i-b"
                                prop="goodsPresell.defaultFine"
                              >
                                <el-input
                                  v-model="form.goodsPresell.defaultFine"
                                  class="w-200"
                                  placeholder="请输入"
                                >
                                  <template slot="append">%</template>
                                </el-input>
                                <span class="tips">&nbsp;注意为已支付定金的比例</span>
                              </el-form-item>
                            </div>
                          </div>
                        </div>
                      </el-card>
                    </div>
                    <!--</el-collapse-transition>-->
                  </el-form-item>

                  <el-form-item
                    label="预售发货"
                    prop="goodsPresell.prepareType"
                  >
                    <el-select
                      v-model="form.goodsPresell.prepareType"
                      placeholder="请选择"
                      style="margin-bottom:6px"
                      class="w-400"
                    >
                      <el-option
                        :value="1"
                        label="支付全款后固定日期发货/自提"
                      />
                      <el-option
                        :value="0"
                        :disabled="form.goodsPresell.type!=='FULL'"
                        label="支付全款后一段时间后发货/自提(限全款预售)"
                      />
                    </el-select>
                    <el-collapse-transition>
                      <div v-if="form.goodsPresell.prepareType === 0">
                        <el-card>
                          <span>顾客支付全款后&nbsp;</span>
                          <el-form-item class="app-display-i-b" prop="goodsPresell.prepareTime">
                            <el-input
                              v-model="form.goodsPresell.prepareTime"
                              class="w-100"
                              maxlength="3"
                              placeholder="请输入"
                            />
                          </el-form-item>
                          <el-form-item class="app-display-i-b" prop="goodsPresell.prepareUnit">
                            <el-select
                              v-model="form.goodsPresell.prepareUnit"
                              placeholder="请选择"
                              class="w-100"
                            >
                              <el-option
                                value="HOURS"
                                label="小时"
                              />
                              <el-option
                                value="DAYS"
                                label="天"
                              />
                            </el-select>
                          </el-form-item>
                          <span>&nbsp;开始发货/自提</span>
                          <span class="tips">定金模式下, 指支付完尾款后</span>
                        </el-card>
                      </div>
                    </el-collapse-transition>
                    <el-collapse-transition>
                      <div v-if="form.goodsPresell.prepareType === 1">
                        <el-card>
                          <el-form-item class="app-display-i-b" prop="goodsPresell.prepareBeginTime">
                            <el-date-picker
                              v-model="form.goodsPresell.prepareBeginTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择日期时间"
                            />
                          </el-form-item>
                          <span>&nbsp;开始发货/自提</span>
                          <span class="tips">&nbsp;到期后仍正常预售，请注意及时调整发货时间，或切换为现货销售</span>
                        </el-card>
                      </div>
                    </el-collapse-transition>
                  </el-form-item>

                  <el-form-item
                    label="全款支付后政策"
                    prop="goodsPresell.cancelRule"
                  >
                    <el-select
                      v-model="form.goodsPresell.cancelRule"
                      placeholder="请选择"
                      style="margin-bottom:6px"
                      class="w-300"
                    >
                      <el-option
                        :value="0"
                        label="全款支付后不可取消订单"
                      />
                      <el-option
                        :value="1"
                        label="发货日期前可免责取消订单"
                      />
                      <el-option
                        :value="2"
                        label="发货前一段固定时间可免责取消订单"
                      />
                    </el-select>
                    <el-collapse-transition>
                      <div v-if="form.goodsPresell.cancelRule === 2">
                        <el-card>
                          <div>
                            <span>发货前&nbsp;</span>
                            <el-form-item class="app-display-i-b" prop="goodsPresell.cancelFreeTime">
                              <el-input
                                v-model="form.goodsPresell.cancelFreeTime"
                                class="w-200"
                                maxlength="3"
                                placeholder="请输入"
                              >
                                <template slot="append">天</template>
                              </el-input>
                            </el-form-item>
                            <span>&nbsp;可免责取消订单</span>
                          </div>

                          <div>
                            <span>超过免责时间取消订单扣除&nbsp;</span>
                            <el-form-item class="app-display-i-b" prop="goodsPresell.cancelChargeType">
                              <el-select
                                v-model="form.goodsPresell.cancelChargeType"
                                placeholder="请选择"
                                class="w-100"
                              >
                                <el-option
                                  :value="0"
                                  label="固定金额"
                                />
                                <el-option
                                  :value="1"
                                  label="一定比例"
                                />
                              </el-select>
                            </el-form-item>
                            <span>&nbsp;违约金为&nbsp;</span>
                            <el-form-item
                              v-if="form.goodsPresell.cancelChargeType===0"
                              class="app-display-i-b"
                              prop="goodsPresell.cancelCharge"
                            >
                              <el-input
                                v-model="form.goodsPresell.cancelCharge"
                                class="w-200"
                                placeholder="请输入"
                              >
                                <template slot="append">元</template>
                              </el-input>
                            </el-form-item>
                            <el-form-item
                              v-if="form.goodsPresell.cancelChargeType===1"
                              class="app-display-i-b"
                              prop="goodsPresell.cancelCharge"
                            >
                              <el-input
                                v-model="form.goodsPresell.cancelCharge"
                                class="w-200"
                                placeholder="请输入"
                              >
                                <template slot="append">%</template>
                              </el-input>
                              <span class="tips">&nbsp;注意指的是订单全款的比例</span>
                            </el-form-item>
                          </div>
                        </el-card>
                      </div>
                    </el-collapse-transition>
                  </el-form-item>
                  <el-form-item label="预售额外条款">
                    <el-input
                      v-model="form.goodsPresell.remark"
                      :autosize="{ minRows: 2,maxRows: 10}"
                      type="textarea"
                      placeholder="请输入(选填)"
                      maxlength="1000"
                      show-word-limit
                      style="max-width: 600px"
                    />
                    <div class="tips">输入的额外条款会在下单时展示给顾客, 注意：顾客需要同意额外条款才可下单。</div>
                  </el-form-item>

                </div>
              </el-collapse-transition>
            </div>
          </div>
          <!--预售 end-->

          <!--购买 start-->
          <div v-show="tabName==='buy'">
            <div v-if="tabOptions['buy'].goodsType.includes(form.goodsType)">
              <el-form-item
                label="参与优惠"
                prop="goodsRule.canUseDiscount"
                class="is-required"
              >
                <el-select
                  v-model="form.goodsRule.canUseDiscount"
                  placeholder="请选择"
                >
                  <el-option
                    :value="true"
                    label="参与优惠"
                  />
                  <el-option
                    :value="false"
                    label="不参与任何优惠"
                  />
                </el-select>
              </el-form-item>
              <div v-if="form.goodsType!==101">
                <el-form-item
                  :rules="rules.cardIdList"
                  label="购买对象"
                  prop="goodsRule.cardIdList"
                >
                  <el-select
                    v-model="form.goodsRule.memberType"
                    placeholder="请选择"
                    style="margin-bottom:6px"
                  >
                    <el-option
                      :value="0"
                      label="不限制"
                    />
                    <el-option
                      :value="1"
                      label="仅会员"
                    />
                    <el-option
                      :value="2"
                      label="自定义"
                    />
                  </el-select>
                  <el-collapse-transition>
                    <div v-if="form.goodsRule.memberType === 2">
                      <el-card>
                        <el-checkbox-group v-model="form.goodsRule.cardIdList">
                          <el-checkbox
                            v-for="item in cardListOptions"
                            :key="item.id"
                            :label="item.id"
                          >{{
                            item.status
                              ? item.categoryName
                              : item.categoryName + '(已停用)'
                          }}
                          </el-checkbox>
                        </el-checkbox-group>
                      </el-card>
                    </div>
                  </el-collapse-transition>
                </el-form-item>
                <el-form-item
                  :rules="rules.limitNum"
                  prop="goodsRule.limitNum"
                  label="商品限购"
                >
                  <el-select
                    v-model="form.goodsRule.limited"
                    placeholder="请选择"
                    style="margin-bottom:6px"
                  >
                    <el-option
                      :value="false"
                      label="不限制"
                    />
                    <el-option
                      :value="true"
                      label="每个顾客限制"
                    />
                  </el-select>
                  <el-input
                    v-if="form.goodsRule.limited"
                    v-model.trim="form.goodsRule.limitNum"
                    maxlength="3"
                    class="w-200"
                    placeholder="1~100"
                  >
                    <template slot="append">件</template>
                  </el-input>
                </el-form-item>
              </div>

            </div>
          </div>
          <!--购买 end-->

          <!--搭配 start-->
          <div v-show="tabName==='parts'">
            <div v-if="tabOptions['parts'].goodsType.includes(form.goodsType)">
              <el-form-item
                label="搭配配件"
                prop="goodsBargains"
              >
                <div>
                  <el-button
                    :disabled="form.goodsBargains.length>=10"
                    type="primary"
                    round
                    icon="el-icon-plus"
                    size="small"
                    style="margin-bottom: 10px"
                    @click="addGoodsBargains"
                  >添加配件
                  </el-button>
                  <span class="app-tips">&nbsp;配件最多可添加十种</span>
                </div>
                <el-table
                  :data="form.goodsBargains"
                  border
                  stripe
                  style="width: 100%;margin-bottom: 5px"
                  size="small"
                >
                  <el-table-column
                    prop="title"
                    label="标题"
                  />
                  <el-table-column
                    prop="categoryName"
                    label="类目"
                  />
                  <el-table-column
                    prop="price"
                    label="价格/元"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.price / 100 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="leastNum" label="最少选购数量" width="160">
                    <template slot="header" slot-scope="scope">
                      <div>最少选购数量</div>
                      <div>（不限制为0）</div>
                    </template>
                    <template slot-scope="scope">
                      <el-form-item :rules="rules.goodsBargainsLeastNum" :prop="'goodsBargains.'+scope.$index">
                        <el-input-number v-model="scope.row.leastNum" :min="0" :max="99999" size="small" label="0~99999" placeholder="不限制为0" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="leastNum" label="最多选购数量" width="160">
                    <template slot="header" slot-scope="scope">
                      <div>最多选购数量</div>
                      <div>（不限制为0）</div>
                    </template>
                    <template slot-scope="scope">
                      <el-form-item :rules="rules.goodsBargainsPerLimitNum" :prop="'goodsBargains.'+scope.$index">
                        <el-input-number v-model="scope.row.perLimitNum" :min="0" :max="99999" size="small" label="0~99999" placeholder="不限制为0" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!--<el-table-column prop="leastNum" label="是否必选" width="100">-->
                  <!--  <template slot-scope="scope">-->
                  <!--    <el-switch-->
                  <!--      v-model="scope.row.leastNum"-->
                  <!--      :active-value="1"-->
                  <!--      :inactive-value="0"-->
                  <!--      inactive-color="#ff4949"-->
                  <!--    />-->
                  <!--    <span v-if="scope.row.leastNum">是</span>-->
                  <!--    <span v-else>否</span>-->
                  <!--  </template>-->
                  <!--</el-table-column>-->
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button type="text" @click="delGoodsBargains(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>

            </div>
          </div>
          <!--搭配 end-->
        </div>
      </el-form>
    </div>
    <!-- 表单 end -->

    <!-- 组件 -->
    <DialogCategory ref="dialogCategory" />
    <DialogPrice ref="dialogPrice" />
    <DialogCouponList ref="dialogCouponList" />
    <DialogMallGoodsSkuTable ref="dialogMallGoodsSkuTable" :goods-types="[101]" :max-sku-num="10-form.goodsBargains.length" />
    <DialogCardCouponTable
      ref="dialogCardCouponTable"
      :card-coupon-type="['cash','discount','exchange','cash_wx_pay','times','gift']"
      :has-checked-ids="hasCheckedCardCouponIds"
    />
  </div>
</template>

<script>
import DialogCardCouponTable from '@/components/DialogCardCouponTable'
import {
  categoryTree,
  getSpecId,
  getAttrId,
  paramList
} from '@/views/wxaMallModule/api/category'
import {
  addProduct,
  updateProduct,
  productDetail
} from '@/views/wxaMallModule/api/product'
import { supportList } from '@/views/wxaMallModule/api/support'
import { getAllVipCardList } from '@/api/vip'
import { imgUploadUrl } from '@/api/upload'
import DialogCategory from './DialogCategory'
import DialogPrice from './DialogPrice'
import draggable from 'vuedraggable'
import { mapGetters } from 'vuex'
import ProductFormValidate from './mixin/ProductFormValidate'
import DialogCouponList from '@/components/DialogCouponList'

export default {
  components: {
    DialogCardCouponTable,
    draggable,
    DialogCategory,
    DialogPrice,
    DialogCouponList
  },
  mixins: [ProductFormValidate],
  props: {
    modeInfo: {
      type: Object,
      default: () => {
        return {
          data: '',
          mode: 'productForm',
          modePage: 'ProductManage'
        }
      }
    }
  },
  data() {
    return {
      // 配置
      categoryTreeOptions: [], // 类目选项
      supportListOptions: [], // 服务选项
      cardListOptions: [], // 卡列表
      goodsTypeOptions: {
        100: '实物商品',
        200: '卡/券包',
        101: '配件商品'
      },
      tabOptions: {
        specs: {
          label: '规格',
          goodsType: [100, 101],
          rules: ['specList', 'originPrice', 'price']
        },
        delivery: {
          label: '配送',
          goodsType: [100],
          rules: ['goodsDelivery']
        },
        coupon: {
          label: '卡券',
          goodsType: [200],
          rules: ['goodsItems', 'couponId', 'couponNum', '']
        },
        param: {
          label: '参数',
          goodsType: [100, 200, 101],
          rules: ['goodsExt.paramList']
        },
        service: {
          label: '服务',
          goodsType: [100, 200],
          rules: []
        },
        photo: {
          label: '图册',
          goodsType: [100, 200, 101],
          rules: ['displayInfo.imageList']
        },
        preSale: {
          label: '预售',
          goodsType: [100],
          rules: ['goodsPresell.depositQuota', 'goodsPresell.preDate', 'goodsPresell.remainingBeginTime', 'goodsPresell.remainingEndTime', 'goodsPresell.defaultFine', 'goodsPresell.prepareTime', 'goodsPresell.prepareBeginTime', 'goodsPresell.cancelFreeTime', 'goodsPresell.cancelCharge']
        },
        buy: {
          label: '购买',
          goodsType: [100, 200, 101],
          rules: ['goodsRule.limitNum', 'goodsRule.cardIdList']
        },
        parts: {
          label: '搭配',
          goodsType: [100],
          rules: ['goodsBargains']
        }
      },
      imageUploadUrl: imgUploadUrl,
      // 状态
      loading: false,
      specInputVisible: false,
      dialogImageVisible: false,
      paramsListLoaded: false,
      // 数据
      mode: 'add',
      tabName: 'specs',
      dialogImageUrl: '',
      hasCheckedCardCouponIds: [],
      form: {
        goodsType: 100, // 商品类型100: 实物商品(物流), 200: 券包(虚拟商品), 300: 同城配送/自提
        // 关联物品
        goodsItems: [],
        couponVerRadio: 'COUPON2',
        categoryId: [], // 商品类目
        categoryIds: [], // 商品类目
        brandId: 0, // 商品品牌
        goodsNo: '', // 商品编码
        barCode: '', // 商品条码
        goodsUnit: '件', // 商品单位
        title: '', // 商品标题
        subTitle: '', // 商品子标题
        description: '', // 商品描述
        specList: [], // 规格信息
        // 规格信息
        skuList: [
          {
            imgUrl: '',
            originPrice: '',
            price: '',
            skuNo: '',
            sn: '',
            specAttrNameList: [],
            specAttrIdsList: [],
            status: 0,
            specAttr1: 0,
            specAttr2: 0,
            specAttr3: 0,
            specAttr4: 0,
            specAttr5: 0,
            specAttr6: 0
          }
        ],
        // 参数 服务信息
        goodsExt: {
          paramList: [],
          supportList: []
        },
        // 限制规则
        goodsRule: {
          canUseDiscount: false,
          limited: false,
          memberType: 0, // 0:所有顾客, 1:会员, 2:仅指定会员
          cardIdList: [],
          limitNum: '',
          payChannels: [1, 2]
        },
        // 预售
        presell: false,
        goodsPresell: {
          type: 'FULL',
          depositType: 0,
          depositQuota: null,
          limitTime: true,
          preDate: null,
          beginTime: null,
          endTime: null,
          afterTheEnd: 0,
          remainingBeginTime: null,
          remainingEndTime: null,
          defaultRule: 0,
          defaultFineType: 0,
          defaultFine: null,
          prepareType: 1,
          prepareTime: null,
          prepareUnit: 'DAYS',
          prepareBeginTime: null,
          cancelRule: 0,
          cancelFreeTime: null,
          cancelChargeType: 0,
          cancelCharge: null,
          remark: null
        },
        // 预览信息
        displayInfo: {
          detailImages: [],
          imageList: []
        },
        goodsDelivery: {
          canExpress: true,
          expressPrepare: null,
          expressPrepareUnit: 'HOURS',
          canLocalDelivery: true,
          localPrepare: null,
          localPrepareUnit: 'HOURS',
          canSelfPickup: true,
          selfPickupPrepare: null,
          selfPickupPrepareUnit: 'HOURS'
        },
        goodsBargains: [], // 加购
        specInputValueExcl: null // specInput临时绑定值
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  watch: {},
  created() {
  },
  mounted() {
    console.log(this.modeInfo)
    // 判断进来是否有id
    if (this.modeInfo.data) {
      this.mode = 'edit'
      this.getDetail(this.modeInfo.data)
    } else {
      this.mode = 'add'
    }
    this.getCategoryTree()
    this.getSupportList()
    this.getCardList()
  },
  methods: {
    /**
     * 数据组
     */
    // 获取详情
    getDetail(goodsId) {
      return new Promise((resolve, reject) => {
        this.loading = true
        productDetail({ goodsId })
          .then((res) => {
            const params = res.data
            // 处理goodsType特殊参数 配送
            if (this.tabOptions.delivery.goodsType.includes(params.goodsType)) {
              if (params.goodsDelivery.canExpress && params.goodsDelivery.expressPrepare) {
                params.goodsDelivery.canExpress = 'truePrepare'
              } else {
                params.goodsDelivery.expressPrepare = 0
                params.goodsDelivery.expressPrepareUnit = 'HOURS'
              }
              if (params.goodsDelivery.canLocalDelivery && params.goodsDelivery.localPrepare) {
                params.goodsDelivery.canLocalDelivery = 'truePrepare'
              } else {
                params.goodsDelivery.localPrepare = 0
                params.goodsDelivery.localPrepareUnit = 'HOURS'
              }
              if (params.goodsDelivery.canSelfPickup && params.goodsDelivery.selfPickupPrepare) {
                params.goodsDelivery.canSelfPickup = 'truePrepare'
              } else {
                params.goodsDelivery.selfPickupPrepare = 0
                params.goodsDelivery.selfPickupPrepareUnit = 'HOURS'
              }
            } else {
              params.goodsDelivery = {
                canExpress: true,
                expressPrepare: 0,
                expressPrepareUnit: 'HOURS',
                canLocalDelivery: true,
                localPrepare: 0,
                localPrepareUnit: 'HOURS',
                canSelfPickup: true,
                selfPickupPrepare: 0,
                selfPickupPrepareUnit: 'HOURS'
              }
            }

            // 处理goodsType特殊参数 预售
            if (this.tabOptions.preSale.goodsType.includes(params.goodsType) && params.presell) {
              // 定金方式
              if (params.goodsPresell.type === 'DEPOSIT' && params.goodsPresell.depositType === 0) {
                // 转元
                params.goodsPresell.depositQuota = this.$math.div(params.goodsPresell.depositQuota, 100, 2)
              }
              if (params.goodsPresell.defaultRule === 2 && params.goodsPresell.defaultFineType === 0) {
                params.goodsPresell.defaultFine = this.$math.div(params.goodsPresell.defaultFine, 100, 2)
              }
              // 预售时间
              if (params.goodsPresell.limitTime) {
                params.goodsPresell.preDate = [params.goodsPresell.beginTime, params.goodsPresell.endTime]
              } else {
                params.goodsPresell.preDate = null
              }
              // 退订
              if (params.goodsPresell.cancelRule === 2 && params.goodsPresell.cancelChargeType === 0) {
                // 转元
                params.goodsPresell.cancelCharge = this.$math.div(params.goodsPresell.cancelCharge, 100, 2)
              }
            } else {
              params.goodsPresell = {
                type: 'FULL',
                depositType: 0,
                depositQuota: null,
                limitTime: true,
                preDate: null,
                beginTime: null,
                endTime: null,
                afterTheEnd: 0,
                remainingBeginTime: null,
                remainingEndTime: null,
                defaultRule: 0,
                defaultFineType: 0,
                defaultFine: null,
                prepareType: 1,
                prepareTime: null,
                prepareUnit: 'DAYS',
                prepareBeginTime: null,
                cancelRule: 0,
                cancelFreeTime: null,
                cancelChargeType: 0,
                cancelCharge: null,
                remark: null
              }
            }

            // 处理goodsType特殊参数 处理卡券
            if (this.tabOptions.coupon.goodsType.includes(params.goodsType)) {
              if (params.goodsItems.length) {
                let version = 2 // 判断是v1 还是v2
                params.goodsItems.some((v, i) => {
                  if (i === 0) {
                    version = v.itemType === 'COUPON' ? 1 : 2
                    return true
                  }
                })
                params.couponVerRadio = version === 2 ? 'COUPON2' : 'COUPON'
              } else {
                params.couponVerRadio = 'COUPON2'
                params.goodsItems = []
              }
            }
            // 处理categoryId
            params.categoryId = params.categoryIds

            // sku价格
            params.skuList.forEach((v) => {
              v.price = v.price / 100
              v.originPrice = v.originPrice ? v.originPrice / 100 : null
            })

            // 购买限制
            if (!params.goodsRule.limited) params.goodsRule.limitNum = ''
            if (params.displayInfo.imageList && params.displayInfo.imageList.length === 1 && params.displayInfo.imageList[0] === 'business/common/detail_goods.png') params.displayInfo.imageList = []

            // 图片列表获取path
            params.displayInfo.imageList = params.displayInfo.imageList.map(
              (v) => {
                return {
                  response: { code: 0, data: { path: v } },
                  url: this.fileBaseUrl + v
                }
              }
            )
            params.displayInfo.detailImages = params.displayInfo.detailImages.map(
              (v) => {
                return {
                  response: { code: 0, data: { path: v } },
                  url: this.fileBaseUrl + v
                }
              }
            )
            params.specList.map((v) => {
              v.inputVisible = false
              v.inputValue = ''
            })
            params.specInputValueExcl = null
            this.changeGoodsType(params.goodsType)
            this.form = params
          })
          .finally(() => {
            this.loading = false
          })
      })
    },

    // 获取类目tree
    getCategoryTree() {
      return new Promise((resolve, reject) => {
        categoryTree()
          .then((res) => {
            this.categoryTreeOptions = this.formatTreeData(res.data)
          })
          .catch((err) => {
          })
          .finally(() => {
          })
      })
    },

    // 递归children设置空
    formatTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
          data[i].children = undefined
        } else {
          this.formatTreeData(data[i].children)
        }
      }
      return data
    },

    // 获取服务
    getSupportList() {
      return new Promise((resolve, reject) => {
        supportList({ type: 1 })
          .then((res) => {
            this.supportListOptions = res.data
            if (this.mode === 'add') {
              this.supportListOptions.forEach((v) => {
                if (v.defaulted) {
                  this.form.goodsExt.supportList.push(v)
                }
              })
            }
          })
      })
    },

    // 获取参数列表
    getParamList() {
      return new Promise((resolve) => {
        if (
          this.mode === 'add' &&
          !this.paramsListLoaded &&
          this.form.categoryIds &&
          this.form.categoryIds.length &&
          this.form.goodsExt.paramList.length === 0
        ) {
          paramList(this.form.categoryIds)
            .then((res) => {
              this.paramsListLoaded = true
              res.data.forEach((v) => {
                this.form.goodsExt.paramList.push({
                  name: v,
                  value: ''
                })
              })
            })
            .finally(() => {
            })
        } else {
          resolve()
        }
      })
    },

    // 获取会员卡
    getCardList() {
      return new Promise((resolve, reject) => {
        getAllVipCardList().then((res) => {
          this.cardListOptions = res.data
        })
      })
    },

    /**
     * 按钮组
     */
    back(refresh = false) {
      this.$emit('update:modeInfo', {
        mode: 'manage',
        modePage: 'ProductManage',
        data: refresh ? 'refresh' : ''
      })
    },

    // 选择类目属性
    openCategory() {
      // 请先选择类目
      if (!this.form.categoryIds || this.form.categoryIds.length == 0) {
        this.$message.warning('请先选择商品类目')
        return
      }
      this.$refs.dialogCategory
        .open({ categoryIds: this.form.categoryIds })
        .then((res) => {
          if (res && res.length) {
            const obj = {}
            const specIdsArr = []
            this.form.specList.forEach((spec) => {
              obj[spec.id] = []
              specIdsArr.push(spec.id)
              spec.attrList.forEach((attr) => {
                obj[spec.id].push(attr.id)
              })
            })
            res.forEach((spec) => {
              const index = specIdsArr.findIndex((item) => item === spec.id)
              if (index !== -1) {
                spec.attrList.forEach((attr) => {
                  attr.inputVisible = false
                  attr.inputValue = ''
                  if (!obj[spec.id].includes(attr.id)) {
                    attr.inputVisible = false
                    attr.inputValue = ''
                    this.form.specList[index].attrList.push(attr)
                  }
                })
              } else {
                spec.attrList.forEach((attr) => {
                  attr.inputVisible = false
                  attr.inputValue = ''
                })
                this.form.specList.push(spec)
              }
            })
            this.skuBuilder()
          }
        })
    },

    // 新增优惠券
    openCouponList() {
      this.hasCheckedCardCouponIds = []
      this.form.goodsItems.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.itemId)
      })
      this.$nextTick(() => {
        this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 2).then((res) => {
          const params = {
            itemType: 'COUPON',
            itemId: res.couponId,
            num: 1,
            itemTitle: res.couponName,
            description: res.description,
            extInfo: null,
            itemImg: null,
            // itemNo: null
            itemNo: res.identityCode
          }
          this.$refs.form.clearValidate(['goodsItems'])
          this.form.goodsItems.push(params)
        })
      })
    },

    //  新增优惠券 v2
    openDialogCardCouponTable() {
      this.hasCheckedCardCouponIds = []
      this.form.goodsItems.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.itemId)
      })
      this.$nextTick(() => {
        this.$refs.dialogCardCouponTable.open().then(res => {
          this.$refs.form.clearValidate(['goodsItems'])
          const couponArr = []
          res.forEach(v => {
            couponArr.push({
              itemType: 'COUPON2',
              itemId: v.couponId,
              num: 1,
              itemTitle: v.couponName,
              description: v.description,
              extInfo: null,
              itemImg: null,
              itemNo: null
            })
          })
          this.form.goodsItems = this.form.goodsItems.concat(couponArr)
        })
      })
    },

    // 删除优惠券
    delCardCoupon(index) {
      this.$refs.form.clearValidate(['couponAward[' + index + '].couponId'])
      this.form.goodsItems.splice(index, 1)
      this.hasCheckedCardCouponIds.splice(index, 1)
    },

    // 显示spec
    showSpecInput() {
      this.specInputVisible = true
      this.$nextTick(() => {
        this.$refs.saveSpecInput.$refs.input.focus()
      })
    },

    // 删除spec
    delSpec(index) {
      this.form.specList.splice(index, 1)
      if (this.form.specList.length <= 3) {
        this.$refs.form.clearValidate(['specList'])
      }
      this.skuBuilder()
    },

    // 新增spec
    addSpec() {
      const inputValue = this.form.specInputValueExcl
      if (inputValue) {
        const flag = this.form.specList.some((v) => {
          if (inputValue === v.title) {
            this.$message.warning('已存在该销售属性')
            return true
          }
        })
        if (flag) {
          return
        }
        getSpecId({ title: inputValue })
          .then((res) => {
            this.form.specList.push({
              title: inputValue,
              id: res.data,
              attrList: [],
              inputVisible: false,
              inputValue: ''
            })
            this.specInputVisible = false
            this.form.specInputValueExcl = ''
          })
      } else {
        this.specInputVisible = false
        this.form.specInputValueExcl = ''
      }
    },

    // 显示attrInput
    showAttrInput(item) {
      // 其它移除
      this.form.specList.forEach((v) => {
        if (v.id !== item.id) {
          v.inputVisible = false
        }
      })
      // 当前激活
      item.inputVisible = true
      this.$forceUpdate()
      this.$nextTick(() => {
        this.$refs.saveAttrInput[0].$refs.input.focus()
      })
    },

    // 新增attr
    addAttr(row) {
      const inputValue = row.inputValue
      if (inputValue) {
        const flag = row.attrList.some((v) => {
          if (inputValue === v.title) {
            return true
          }
        })
        if (flag) {
          row.inputVisible = false
          row.inputValue = ''
          return
        }
        getAttrId({ specId: row.id, title: inputValue })
          .then((res) => {
            row.attrList.push({
              title: inputValue,
              id: res.data
            })
            row.inputValue = ''
            this.skuBuilder()
          })
          .catch((err) => {
          })
          .finally(() => {
          })
      } else {
        row.inputVisible = false
        row.inputValue = ''
      }
    },

    // 关闭attr
    closeAttr(row, index) {
      row.splice(index, 1)
      this.skuBuilder()
    },

    // 上传sku图片
    handleSkuImgBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1)
    },
    handleSkuImgSuccess(res, file, index) {
      console.log(index)
      if (res.code === 0) {
        this.form.skuList[index].imgUrl = res.data.path
      } else {
        this.$message.error(res.msg)
      }
    },

    // 批量改价
    openDialogPrice() {
      this.$refs.dialogPrice.open().then((res) => {
        this.form.skuList.forEach((v) => {
          v.price = res.price
          v.originPrice = res.originPrice
        })
      })
    },

    // 增加参数
    addParams() {
      this.form.goodsExt.paramList.push({
        name: '',
        value: ''
      })
    },

    // 删除参数
    delParams(index) {
      this.form.goodsExt.paramList.splice(index, 1)
    },

    // 上传商品图片
    handleImageListSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.form.displayInfo.imageList = fileList
        this.$refs.form.clearValidate(['displayInfo.imageList'])
      } else {
        this.$message.error(res.msg)
      }
    },
    handleImageListRemove(v, i) {
      this.form.displayInfo.imageList.splice(i, 1)
    },

    // 上传详情图片
    handleDetailImagesSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.form.displayInfo.detailImages = fileList
        this.$refs.form.clearValidate(['detailImages'])
      } else {
        this.$message.error(res.msg)
      }
    },
    handleDetailImagesRemove(v, i) {
      this.form.displayInfo.detailImages.splice(i, 1)
    },

    // 上传通用
    handleDisplayInfoBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1)
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    handleExceed() {
      this.$message.error('最多上传10张')
    },

    // 保存
    submit() {
      this.$refs.form.validate((valid, result) => {
        if (!valid) {
          console.log(Object.keys(result))
          const tabName = []
          for (const key in this.tabOptions) {
            if (this.tabOptions[key].goodsType.includes(this.form.goodsType)) {
              this.tabOptions[key].rules.some((rule) => {
                return Object.keys(result).some((err) => {
                  if (err.indexOf(rule) !== -1) {
                    tabName.push(key)
                    return true
                  }
                })
              })
            }
          }
          if (tabName.length) this.tabName = tabName[0]
          this.$message.error('请检查填写完整信息')
        } else {
          const params = JSON.parse(JSON.stringify(this.form))
          // 处理goodsType特殊参数 配送
          if (this.tabOptions.delivery.goodsType.includes(params.goodsType)) {
            if (params.goodsDelivery.canExpress === 'truePrepare') {
              params.goodsDelivery.canExpress = true
            } else {
              params.goodsDelivery.expressPrepare = 0
              params.goodsDelivery.expressPrepareUnit = 'HOURS'
            }
            if (params.goodsDelivery.canLocalDelivery === 'truePrepare') {
              params.goodsDelivery.canLocalDelivery = true
            } else {
              params.goodsDelivery.localPrepare = 0
              params.goodsDelivery.localPrepareUnit = 'HOURS'
            }
            if (params.goodsDelivery.canSelfPickup === 'truePrepare') {
              params.goodsDelivery.canSelfPickup = true
            } else {
              params.goodsDelivery.selfPickupPrepare = 0
              params.goodsDelivery.selfPickupPrepareUnit = 'HOURS'
            }
          } else {
            params.goodsDelivery = {
              canExpress: true,
              expressPrepare: 0,
              expressPrepareUnit: 'HOURS',
              canLocalDelivery: true,
              localPrepare: 0,
              localPrepareUnit: 'HOURS',
              canSelfPickup: true,
              selfPickupPrepare: 0,
              selfPickupPrepareUnit: 'HOURS'
            }
          }

          // 处理goodsType特殊参数 预售
          if (this.tabOptions.preSale.goodsType.includes(params.goodsType)) {
            if (params.presell) {
              // 定金方式
              if (params.goodsPresell.type === 'DEPOSIT') {
                // 定金转分
                if (params.goodsPresell.depositType === 0) params.goodsPresell.depositQuota = this.$math.mul(params.goodsPresell.depositQuota, 100, 0)
                // 尾款
                if (params.goodsPresell.defaultRule === 0 || params.goodsPresell.defaultRule === 1) {
                  params.goodsPresell.defaultFine = ''
                } else if (params.goodsPresell.defaultRule === 2 && params.goodsPresell.defaultFineType === 0) {
                  params.goodsPresell.defaultFine = this.$math.mul(params.goodsPresell.defaultFine, 100, 0)
                }
              } else {
                params.goodsPresell.depositType = 0
                params.goodsPresell.depositQuota = ''
                params.goodsPresell.defaultFineType = 0
                params.goodsPresell.defaultRule = 0
                params.goodsPresell.defaultFine = ''
              }

              // 预售时间
              if (params.goodsPresell.limitTime) {
                params.goodsPresell.beginTime = params.goodsPresell.preDate[0]
                params.goodsPresell.endTime = params.goodsPresell.preDate[1]
              } else {
                params.goodsPresell.beginTime = ''
                params.goodsPresell.endTime = ''
              }
              delete params.goodsPresell.preDate

              // 预售发货
              if (params.goodsPresell.prepareType === 0) {
                params.goodsPresell.prepareBeginTime = ''
              } else {
                params.goodsPresell.prepareUnit = 'DAYS'
                params.goodsPresell.prepareTime = ''
              }

              // 退订
              if (params.goodsPresell.cancelRule === 0 || params.goodsPresell.cancelRule === 1) {
                params.goodsPresell.cancelFreeTime = null
                params.goodsPresell.cancelChargeType = 0
                params.goodsPresell.cancelCharge = ''
              } else {
                // 转化分
                if (params.goodsPresell.cancelChargeType === 0) params.goodsPresell.cancelCharge = this.$math.mul(params.goodsPresell.cancelCharge, 100, 0)
              }
            } else {
              delete params.goodsPresell
            }
          } else {
            delete params.goodsPresell
          }

          // 处理goodsType特殊参数 处理卡券
          if (!this.tabOptions.coupon.goodsType.includes(params.goodsType)) {
            params.goodsItems = []
          }

          // 处理goodsType特殊参数 搭配
          if (!this.tabOptions.parts.goodsType.includes(params.goodsType)) {
            params.goodsBargains = []
          }

          // 处理goodsType特殊参数 购买限制 购买对象
          if (params.goodsType === 101) {
            params.goodsRule.memberType = 0
            params.goodsRule.cardIdList = []
            params.goodsRule.limitNum = ''
          }

          // 类目
          params.categoryId = params.categoryIds[this.form.categoryIds.length - 1]

          // 格式化sku金额
          params.skuList.forEach((v) => {
            v.price = this.$math.mul(v.price, 100, 0)
            v.originPrice = v.originPrice
              ? this.$math.mul(v.originPrice, 100, 0)
              : 0
          })

          // 购买限制
          if (!params.goodsRule.limited) params.goodsRule.limitNum = ''

          // 图片列表获取path
          params.displayInfo.imageList = params.displayInfo.imageList.map(
            (v) => {
              if (
                v.response &&
                v.response.code === 0 &&
                v.response.data &&
                v.response.data.path
              ) {
                return v.response.data.path
              }
            }
          )
          params.displayInfo.detailImages = params.displayInfo.detailImages.map(
            (v) => {
              if (
                v.response &&
                v.response.code === 0 &&
                v.response.data &&
                v.response.data.path
              ) {
                return v.response.data.path
              }
            }
          )
          this.loading = true
          if (params.displayInfo.imageList.length === 0) params.displayInfo.imageList = ['business/common/detail_goods.png']
          if (params.goodsId) {
            updateProduct(params)
              .then(() => {
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.back(true)
              })
              .finally(() => {
                this.loading = false
              })
          } else {
            addProduct(params)
              .then(() => {
                this.$notify({
                  title: '成功',
                  message: '新增成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.back(true)
              })
              .finally(() => {
                this.loading = false
              })
          }
        }
      })
    },

    /**
     * 状态组
     */
    /**
     * 方法组
     */
    // 生成sku
    skuBuilder() {
      const specList = this.form.specList
      // 获取二维组合 [[attr1],[attr2],[attr3]]
      const attrIdsArr = []
      const attrNameObj = {}
      specList.forEach((spec, specIndex) => {
        const attrIds = []
        spec.attrList.forEach((attr, attrIndex) => {
          attrIds.push(attr.id)
          attrNameObj[attr.id] = attr.title
        })
        attrIdsArr.push(attrIds)
      })

      // 获取sku所有组合
      const skuIdsArr = skuList(...attrIdsArr)

      // 生成table列表 匹配原有表格数据存在则不插新数据
      const tableListNew = []
      skuIdsArr.forEach((idsArr) => {
        const specAttrNameList = []
        const skuObj = {
          imgUrl: '',
          originPrice: '',
          price: '',
          skuNo: '',
          sn: '',
          specAttrNameList: [],
          specAttrIdsList: idsArr,
          status: 0,
          specAttr1: 0,
          specAttr2: 0,
          specAttr3: 0,
          specAttr4: 0,
          specAttr5: 0,
          specAttr6: 0
        }
        idsArr.forEach((id, idIndex) => {
          specAttrNameList.push(attrNameObj[id])
          skuObj['specAttr' + (idIndex + 1)] = id
        })
        skuObj.specAttrNameList = specAttrNameList
        tableListNew.push(skuObj)
      })

      // 判断是否已经存在 存在则使用旧数据
      tableListNew.forEach((newItem, newItemIndex) => {
        this.form.skuList.forEach((oldItem) => {
          const newItemString = JSON.stringify(newItem.specAttrNameList.sort())
          const oldItemString = JSON.stringify(oldItem.specAttrNameList.sort())
          if (newItemString === oldItemString) {
            tableListNew.splice(newItemIndex, 1, oldItem)
          }
        })
      })

      // 赋值
      this.form.skuList = tableListNew

      // 生成所有sku组合
      function skuList() {
        return Array.prototype.reduce.call(
          arguments,
          function(a, b) {
            if (b.length === 0) {
              return a
            }
            var ret = []
            a.forEach(function(a) {
              b.forEach(function(b) {
                ret.push(a.concat([b]))
              })
            })
            return ret
          },
          [[]]
        )
      }
    },

    // 添加配件
    addGoodsBargains() {
      let checkedSkuIds = []
      checkedSkuIds = this.form.goodsBargains.map(v => {
        return v.skuId
      })
      this.$refs.dialogMallGoodsSkuTable.open({ checkedSkuIds }).then(res => {
        if (res && res.length) {
          const list = res.map(v => {
            return {
              categoryName: v.goods.category,
              goodsId: v.goods.goodsId,
              leastNum: 0,
              perLimitNum: 1,
              price: v.skuInfo.price,
              skuId: v.skuInfo.skuId,
              title: v.goods.title,
              type: 0
            }
          })
          this.form.goodsBargains = this.form.goodsBargains.concat(list)
        }
      })
    },

    // 移除配件
    delGoodsBargains(index) {
      this.form.goodsBargains.splice(index, 1)
      if (this.form.goodsBargains.length <= 10) {
        this.$refs.form.clearValidate(['goodsBargains'])
      }
    },

    // tab click
    tabClick(tab, e) {
      if (tab.name === 'param') this.getParamList()
    },

    /**
     * 状态组
     */
    // 券版本变动
    couponVerRadioChange(v) {
      this.form.goodsItems = []
      this.$refs.form.clearValidate(['goodsItems'])
    },

    // 预售类型改变
    goodsPresellTypeChange(val) {
      if (val === 'DEPOSIT' && !this.form.goodsPresell.limitTime) this.form.goodsPresell.limitTime = true
      if (val === 'DEPOSIT' && this.form.goodsPresell.prepareType === 0) this.form.goodsPresell.prepareType = 1
    },

    // 商品类型变动
    changeGoodsType(val) {
      if (val === 101) {
        this.form.specList = []
        this.form.skuList = [{
          imgUrl: '',
          originPrice: '',
          price: '',
          skuNo: '',
          sn: '',
          specAttrNameList: [],
          specAttrIdsList: [],
          status: 0,
          specAttr1: 0,
          specAttr2: 0,
          specAttr3: 0,
          specAttr4: 0,
          specAttr5: 0,
          specAttr6: 0
        }]
      }
      for (const key in this.tabOptions) {
        if (this.tabOptions[key].goodsType.includes(val)) {
          if (key === this.tabName) {
            return
          } else {
            this.tabName = key
            return
          }
        }
      }
    }
  }
}
</script>
<style rel="stylesheet/scss"
       lang="scss"
       scoped>
/*重置*/
.tab-content ::v-deep {
  .el-tabs__header {
    margin-bottom: 0;
    //background-color: #fff;
    border-radius: 0 0 5px 5px;
  }

  .el-tabs__nav-wrap::after {
    background-color: #fff;
  }

  .el-tabs__active-bar {
    height: 4px;
  }
}

.el-divider {
  margin: 10px 0 20px;
}

/*表单*/
.form-container {

}

/*表单基础*/
.base-content {
  padding: 10px 20px 0;
  background-color: #fff;
  border-radius: 5px;
}

/*表单基础*/
.additional-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  margin-top: 10px;
}

/* 通用 */
.w-100 {
  width: 100px;
}

.w-200 {
  width: 200px;
}

.w-300 {
  width: 300px;
}

.w-400 {
  width: 400px;
}

.w-700 {
  width: 700px;
}

.w-300-h-32 {
  width: 300px;
  height: 32px;
}

.w-450-h-32 {
  width: 450px;
  height: 32px;
}

.m-t-18 {
  margin-top: 18px;
}

/* 表单行内块 */
.inline-block {
  display: inline-block;
}

.tips {
  font-size: 12px;
  color: #606266;
}

/* 券列表 */
.card-coupon-container {
  max-width: 900px;
}

/* 属性卡片 */
.spec-card {
  max-width: 800px;

  ::v-deep .el-card__header {
    padding: 5px 20px;
  }

  .el-tag {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.spec-card {
  margin-bottom: 10px;
}

/* sku图片 */
.sku-img {
  width: 60px;
  height: 60px;
  box-shadow: 0 0px 2px 0 rgba(0, 0, 0, 0.1);
}

/* 上传商品图 */

.upload-img-list-container {
  margin: 0;
  display: inline;
  vertical-align: top;
  cursor: pointer;

  .img-item {
    position: relative;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    height: 200px;
    width: 200px;
    margin: 0 8px 8px 0;
    display: inline-block;

    .handle-icon {
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      font-size: 20px;

      .icon {
        margin: 10px;
        display: none;
      }
    }

    &:hover {
      color: #fff;

      .handle-icon {
        background-color: rgba(0, 0, 0, 0.5);

        .icon {
          display: block;
        }
      }
    }
  }

}

.upload-container ::v-deep {
  .el-upload-dragger {
    width: 200px;
    height: 200px;
    border: none;
  }

  .el-icon-upload {
    margin-top: 50px;
  }

  .el-upload--picture-card {
    line-height: 1;
    width: 200px;
    height: 200px;
    border: none;
  }

  .el-upload-list__item {
    width: 200px;
    height: 200px;
  }
}
</style>
